﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.UPMS.Model;
using NHibernate.Criterion;
using ZDSoft.UPMS.Model.SystemPart;
using ZDSoft.UPMS.Component.SystemPart;
using ZDSoft.UPMS.Service.SystemPart;
using ZDSoft.UPMS.Core;
using System.Text;

namespace ZDSoft.UPMS.Web.Controllers
{
    public class UserController : Controller
    {
        private IList<ICriterion> Listquery { get; set; }
        //
        // GET: /User/
        public ActionResult Index()
        {
            return View();
        }

        public string getusercount()
        {
            IList<Model.SystemPart.User> user = Container.Instance.Resolve<IUserService>().FindAll();
            return user.Count.ToString();
        }

        private IList<ICriterion> GetCondition(string userName = "")
        {
            List<ICriterion> queryConditions = new List<ICriterion>();
            if (!string.IsNullOrEmpty(userName))
            {
                queryConditions.Add(new LikeExpression("Account", userName));
            }
            return queryConditions;
        }

        public JsonResult GetPageds(int pageIndex, int pageSize, string strSearchProperty,
           string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            string userna = Request.QueryString["usernam"].ToString();



            IList<ICriterion> queryConditions = GetCondition(userna);
            IList<Order> orderList = new List<Order>();
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<User> list = new List<User>();
            IList<User> users = Core.Container.Instance.Resolve<IUserService>().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);
            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (User user in users)
            {
                user.TeacherTeachingCourses = null;
                user.Organization = null;
                user.Scores = null;
                user.Roles = null;
                user.Situations = null;

                list.Add(user);
            }
            list.Add(new User() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public JsonResult GetPaged(int pageIndex, int pageSize, string strSearchProperty,
           string strSearchCondition, string strSortProperty, string strSortCondition)
        {
            IList<ICriterion> queryConditions = new List<ICriterion>();
            IList<Order> orderList = new List<Order>();
            if (strSearchProperty != "")
            {
                string[] searchProperties = strSearchProperty.Split(',');
                string[] searchConditions = strSearchCondition.Split(',');
                queryConditions = new List<ICriterion>();
                for (int i = 0; i < searchProperties.Length; i++)
                {
                    queryConditions.Add(Expression.Eq(searchProperties[i], searchConditions[i]));
                }
            }
            if (strSortProperty != "")
            {
                string[] sortProperties = strSortProperty.Split(',');
                string[] sortConditions = strSortCondition.Split(',');
                orderList = new List<Order>();
                for (int i = 0; i < sortProperties.Length; i++)
                {
                    if (sortConditions[i] == "asc")
                    {
                        orderList.Add(new Order(sortProperties[i], true));
                    }
                    else
                    {
                        orderList.Add(new Order(sortProperties[i], false));
                    }
                }
            }

            int count;
            int pageNum;

            IList<User> list = new List<User>();
            IList<User> users = Core.Container.Instance.Resolve<IUserService>().GetPaged(queryConditions, orderList, pageIndex, pageSize, out count);
            int tmpcountI = count / pageSize;
            float temCountF = float.Parse(count.ToString()) / float.Parse(pageSize.ToString());
            if (temCountF > float.Parse(tmpcountI.ToString()))
            {
                pageNum = tmpcountI + 1;
            }
            else
            {
                pageNum = tmpcountI;
            }

            foreach (User user in users)
            {
                user.TeacherTeachingCourses = null;
                user.Organization = null;
                user.Scores = null;
                user.Roles = null;
                user.Situations = null;

                list.Add(user);
            }
            list.Add(new User() { ID = pageNum });
            JsonResult result = this.Json(list, JsonRequestBehavior.AllowGet);
            return result;
        }

        public ActionResult Create()
        {
            IList<Role> role = Container.Instance.Resolve<IRoleService>().FindAll();
            IList<Model.BusinessPart.Organization> organization = Container.Instance.Resolve<IUserService>().findall();
            ViewBag.ztreea = GetJigou(organization);
            ViewBag.role = GetJuese(role);
            return View();
        }

        public string GetJigou(IList<Model.BusinessPart.Organization> organization)
        {
            foreach (Model.BusinessPart.Organization item in organization)
            {
                if (item.SubOrganization == null)
                {
                    ore.Add(item);
                    digui(item.Organizations);
                }
            }
            string sbbb = "";
            StringBuilder sb = new StringBuilder("[");
            foreach (Model.BusinessPart.Organization organ in ore)
            {
                if (organ.SubOrganization != null)
                {
                    sb.Append("{ id: " + organ.ID + ", pId: " + organ.SubOrganization.ID + ", name: \'" + organ.Name + "\', icon: \'../../Scripts/zTree/zTreeStyle/img/diy/user.png\'},");
                }
                else
                {
                    sb.Append("{ id: " + organ.ID + ", pId: 0, name: \'" + organ.Name + "\', icon: \"../../Scripts/zTree/zTreeStyle/img/diy/users.png\", open:true},");
                }
            }
            sbbb = sb.ToString().Substring(0, sb.Length - 1) + "]";
            return sbbb;
        }
       
        public string GetJuese(IList<Model.SystemPart.Role> role)
        {
            StringBuilder sb1 = new StringBuilder("[");
            sb1.Append("{ id:1, pId:0, name:\'请选择角色\', icon:\'../../Scripts/zTree/zTreeStyle/img/diy/users.png\', nocheck:true, open:true},");
            foreach (ZDSoft.UPMS.Model.SystemPart.Role item in role)
            {
                sb1.Append("{ id:" + item.ID + ", pId:1, name:\"" + item.Name + "\", chkDisabled:false, icon:\'../../Scripts/zTree/zTreeStyle/img/diy/users.png\'},");
            }
            return sb1.ToString().Substring(0, sb1.Length - 1) + "]";
        }
        public string getrepituser(string Account)
        {
            IList<ICriterion> quer = new List<ICriterion>();
            quer.Add(new LikeExpression("Account", Account));
            IList<Model.SystemPart.User> isuser = Container.Instance.Resolve<IUserService>().Find(quer);
            if (isuser.Count > 0)
            {
                return isuser.Count.ToString();
            }
            else
            {
                return "-1";
            }
        }
        
        public string Creater(string roleIDs, string Account, string Name, string IsActive, string organ)
        {
            string c = "1";
            IList<Role> roles = new List<Role>();
            Model.SystemPart.User user = new User();
            string[] rolesid = roleIDs.Split(',');
            for (int i = 0; i < rolesid.Length; i++)
            {
                if (rolesid[i] != "")
                {
                    roles.Add(Container.Instance.Resolve<IRoleService>().FindByID(Convert.ToInt32(rolesid[i])));
                }
            }
            user.Account = Account;
            user.IsActive = Boolean.Parse(IsActive.ToString());
            user.Name = Name;
            user.Password = App.AppHelper.EncodeMd5("123456");
            user.Roles = roles;
            user.IsReset = false;
            try
            {
                user.Organization = Container.Instance.Resolve<IUserService>().Getone(Convert.ToInt32(organ));
                Container.Instance.Resolve<IUserService>().Create(user);
            }
            catch {
                c = "-1";
            }
            return c;
        }

        public ActionResult Logout(int id)
        {
            Model.SystemPart.User user = Container.Instance.Resolve<IUserService>().FindByID(id);
            if (user.IsActive)
            {
                user.IsActive = false;
            }
            else
            {
                user.IsActive = true;
            }
            Container.Instance.Resolve<IUserService>().Update(user);
            return RedirectToAction("Index");
        }

        public ActionResult Update(int id)
        {
            IList<Role> role = Container.Instance.Resolve<IRoleService>().FindAll();
            IList<Model.BusinessPart.Organization> organization = Container.Instance.Resolve<IUserService>().findall();
            ViewBag.ztreea = GetJigou(organization);
            User user = Container.Instance.Resolve<IUserService>().FindByID(id);
            TempData["organ"] = user.Organization;
            StringBuilder sb1 = new StringBuilder("[");
            sb1.Append("{ id:1, pId:0, name:\'请选择角色\', icon:\'../../Scripts/zTree/zTreeStyle/img/diy/users.png\', nocheck:true, open:true},");
            int c = user.Roles.Count;
            foreach (ZDSoft.UPMS.Model.SystemPart.Role item in role)
            {
                for (int i = 0; i < c; i++)
                {
                    if (item.ID == user.Roles[i].ID)
                    {
                        sb1.Append("{ id:" + item.ID + ", pId:1, name:\'" + item.Name + "\', chkDisabled:false, checked:true, icon:\"../../Scripts/zTree/zTreeStyle/img/diy/user.png\"},");
                        break;
                    }
                    else if (i == c - 1)
                    {
                        sb1.Append("{ id:" + item.ID + ", pId:1, name:\'" + item.Name + "\', chkDisabled:false, icon:\"../../Scripts/zTree/zTreeStyle/img/diy/user.png\"},");
                    }
                }
            }
            ViewBag.role = sb1.ToString().Substring(0, sb1.Length - 1) + "]";
            ViewBag.temp = GetJuese(role);
            return View(user);
        }
        [HttpPost]
        public ActionResult Update(int id, User user, string getroles, string jigou)
        {
            Model.SystemPart.User newuser = Container.Instance.Resolve<IUserService>().FindByID(id);
            newuser.Name = user.Name;
            newuser.Account = user.Account;
            if (getroles != "")
            {
                IList<Role> role = new List<Role>();
                foreach (string item in getroles.Split(','))
                {
                    if (item != "")
                    {
                        role.Add(Container.Instance.Resolve<IRoleService>().FindByID(Convert.ToInt32(item)));
                    }
                }
                newuser.Roles = role;
            }
            if (jigou != "")
            {
                newuser.Organization = Container.Instance.Resolve<IUserService>().Getone(Convert.ToInt32(jigou));
            }


            Container.Instance.Resolve<IUserService>().Update(newuser);
            return RedirectToAction("Index");
        }

        IList<UPMS.Model.BusinessPart.Organization> ore = new List<UPMS.Model.BusinessPart.Organization>();
        public void digui(IList<Model.BusinessPart.Organization> organe)
        {
            foreach (Model.BusinessPart.Organization item1 in organe)
            {
                ore.Add(item1);
                if (item1.Organizations.Count > 0)
                {
                    digui(item1.Organizations);
                }
            }
        }
        public ActionResult ResetPassword()
        {
            return View();
        }
        public ActionResult ResetPassw(int ID)
        {
            User u = Core.Container.Instance.Resolve<IUserService>().FindByID(ID);
            u.Password = App.AppHelper.EncodeMd5("123456");
            u.IsReset = false;
            Core.Container.Instance.Resolve<IUserService>().Update(u);
            return RedirectToAction("ResetPassword");
        }
    }
}
